<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>多国家路径规划系统</title>
    <link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script src="https://unpkg.com/element-plus/dist/index.full.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css">
    <script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', '微软雅黑', Arial, sans-serif;
        }
        .container {
            display: flex;
            height: 100vh;
        }
        .sidebar {
            width: 350px;
            background: #f5f5f5;
            border-right: 1px solid #e0e0e0;
            overflow-y: auto;
        }
        .map-container {
            flex: 1;
            position: relative;
        }
        #map {
            width: 100%;
            height: 100%;
        }
        .control-panel {
            padding: 20px;
        }
        .status-card {
            background: white;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .route-info {
            background: white;
            border-radius: 8px;
            padding: 15px;
            margin-top: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .route-segment {
            border-left: 3px solid #409eff;
            padding-left: 10px;
            margin-bottom: 10px;
            background: #f8f9fa;
            border-radius: 4px;
        }
        .map-controls {
            position: absolute;
            top: 10px;
            right: 10px;
            z-index: 1000;
            background: white;
            padding: 10px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
    </style>
</head>
<body>
    <div id="app">
        <div class="container">
            <!-- 侧边栏 -->
            <div class="sidebar">
                <div class="control-panel">
                    <h2>多国家路径规划系统</h2>
                    
                    <!-- 国家选择 -->
                    <el-form :model="form" label-width="80px">
                        <el-form-item label="选择国家">
                            <el-select v-model="form.countryCode" placeholder="请选择国家" @change="onCountryChange">
                                <el-option 
                                    v-for="country in countries" 
                                    :key="country.code" 
                                    :label="country.name" 
                                    :value="country.code">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-form>

                    <!-- 网络状态 -->
                    <div class="status-card">
                        <h4>网络状态</h4>
                        <div v-if="networkStatus">
                            <p><strong>状态:</strong> {{ networkStatus.status }}</p>
                            <p><strong>路网段数:</strong> {{ networkStatus.networkCount }}</p>
                            <p><strong>总长度:</strong> {{ formatDistance(networkStatus.totalLength) }}</p>
                            <p><strong>表名:</strong> {{ networkStatus.tableName }}</p>
                        </div>
                        <div v-else>
                            <p>请选择国家</p>
                        </div>
                    </div>

                    <!-- 路径规划 -->
                    <el-form :model="form" label-width="80px">
                        <el-form-item label="起点">
                            <el-input v-model="form.startPoint" placeholder="POINT(经度 纬度)" type="textarea" :rows="2"></el-input>
                        </el-form-item>
                        <el-form-item label="终点">
                            <el-input v-model="form.endPoint" placeholder="POINT(经度 纬度)" type="textarea" :rows="2"></el-input>
                        </el-form-item>
                        <el-form-item label="搜索半径">
                            <el-input-number v-model="form.searchRadius" :min="100" :max="5000" :step="100"></el-input-number>
                            <span style="margin-left: 10px;">米</span>
                        </el-form-item>
                        <el-form-item label="最大距离">
                            <el-input-number v-model="form.maxDistance" :min="1000" :max="100000" :step="1000"></el-input-number>
                            <span style="margin-left: 10px;">米</span>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="planRoute" :loading="planning">开始规划</el-button>
                            <el-button @click="clearRoute">清除路径</el-button>
                        </el-form-item>
                    </el-form>

                    <!-- 路径信息 -->
                    <div v-if="routeResult" class="route-info">
                        <h4>路径信息</h4>
                        <div v-if="routeResult.success">
                            <p><strong>总距离:</strong> {{ formatDistance(routeResult.totalDistance) }}</p>
                            <p><strong>路径段数:</strong> {{ routeResult.segmentCount }}</p>
                            <p><strong>起点节点:</strong> {{ routeResult.startNodeId }}</p>
                            <p><strong>终点节点:</strong> {{ routeResult.endNodeId }}</p>
                            
                            <div v-if="routeResult.segments && routeResult.segments.length > 0">
                                <h5>路径详情</h5>
                                <div v-for="(segment, index) in routeResult.segments" :key="index" class="route-segment">
                                    <p><strong>段 {{ index + 1 }}:</strong> {{ segment.name || '未命名道路' }}</p>
                                    <p><strong>长度:</strong> {{ formatDistance(segment.length) }}</p>
                                    <p><strong>起点:</strong> {{ segment.source }} → <strong>终点:</strong> {{ segment.target }}</p>
                                </div>
                            </div>
                        </div>
                        <div v-else>
                            <p style="color: #f56c6c;">{{ routeResult.errorMessage }}</p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 地图区域 -->
            <div class="map-container">
                <div id="map"></div>
                <div class="map-controls">
                    <el-button @click="centerMap" size="small">居中</el-button>
                    <el-button @click="toggleFullscreen" size="small">全屏</el-button>
                </div>
            </div>
        </div>
    </div>

    <script>
        const { createApp } = Vue;
        const { ElMessage } = ElementPlus;

        createApp({
            data() {
                return {
                    baseURL: '/api',
                    map: null,
                    countries: [],
                    networkStatus: null,
                    form: {
                        countryCode: '',
                        startPoint: 'POINT(116.4074 39.9042)',
                        endPoint: 'POINT(121.4737 31.2304)',
                        searchRadius: 1000,
                        maxDistance: 50000
                    },
                    planning: false,
                    routeResult: null,
                    routeLayer: null
                }
            },
            mounted() {
                this.initMap();
                this.loadCountries();
            },
            methods: {
                // 初始化地图
                initMap() {
                    this.map = L.map('map').setView([39.9042, 116.4074], 6);
                    
                    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                        attribution: '© OpenStreetMap contributors'
                    }).addTo(this.map);

                    // 添加点击事件
                    this.map.on('click', (e) => {
                        const point = `POINT(${e.latlng.lng} ${e.latlng.lat})`;
                        if (!this.form.startPoint || this.form.startPoint === '') {
                            this.form.startPoint = point;
                        } else {
                            this.form.endPoint = point;
                        }
                    });
                },

                // 加载国家列表
                async loadCountries() {
                    try {
                        const response = await axios.get(`${this.baseURL}/routing/countries`);
                        if (response.data.code === 200) {
                            this.countries = response.data.data;
                            if (this.countries.length > 0) {
                                this.form.countryCode = this.countries[0].code;
                                this.onCountryChange();
                            }
                        }
                    } catch (error) {
                        console.error('加载国家列表失败:', error);
                        ElMessage.error('加载国家列表失败');
                    }
                },

                // 国家改变事件
                async onCountryChange() {
                    if (this.form.countryCode) {
                        await this.checkNetworkStatus();
                    }
                },

                // 检查网络状态
                async checkNetworkStatus() {
                    try {
                        const response = await axios.get(`${this.baseURL}/routing/status`, {
                            params: { countryCode: this.form.countryCode }
                        });
                        if (response.data.code === 200) {
                            this.networkStatus = response.data.data;
                        }
                    } catch (error) {
                        console.error('检查网络状态失败:', error);
                        ElMessage.error('检查网络状态失败');
                    }
                },

                // 路径规划
                async planRoute() {
                    if (!this.form.countryCode) {
                        ElMessage.error('请选择国家');
                        return;
                    }

                    if (!this.form.startPoint || !this.form.endPoint) {
                        ElMessage.error('请设置起点和终点');
                        return;
                    }

                    try {
                        this.planning = true;
                        this.clearRoute();

                        const response = await axios.post(`${this.baseURL}/routing/plan`, {
                            startPoint: this.form.startPoint,
                            endPoint: this.form.endPoint,
                            countryCode: this.form.countryCode,
                            searchRadius: this.form.searchRadius,
                            maxDistance: this.form.maxDistance
                        });

                        if (response.data.code === 200) {
                            this.routeResult = response.data.data;
                            this.displayRoute();
                            ElMessage.success('路径规划成功');
                        } else {
                            this.routeResult = { success: false, errorMessage: response.data.msg };
                            ElMessage.error(response.data.msg);
                        }

                    } catch (error) {
                        console.error('路径规划失败:', error);
                        this.routeResult = { success: false, errorMessage: error.message };
                        ElMessage.error('路径规划失败: ' + error.message);
                    } finally {
                        this.planning = false;
                    }
                },

                // 显示路径
                displayRoute() {
                    if (!this.routeResult || !this.routeResult.success || !this.routeResult.segments) {
                        return;
                    }

                    // 清除之前的路径
                    if (this.routeLayer) {
                        this.map.removeLayer(this.routeLayer);
                    }

                    this.routeLayer = L.layerGroup();

                    // 添加路径段
                    this.routeResult.segments.forEach((segment, index) => {
                        if (segment.geom) {
                            try {
                                // 解析几何数据并添加到地图
                                const coords = this.parseGeometry(segment.geom);
                                if (coords && coords.length > 1) {
                                    const latlngs = coords.map(coord => [coord[1], coord[0]]);
                                    const polyline = L.polyline(latlngs, {
                                        color: index === 0 ? '#ff0000' : '#409eff',
                                        weight: 4,
                                        opacity: 0.8
                                    });
                                    
                                    // 添加弹出信息
                                    polyline.bindPopup(`
                                        <strong>${segment.name || '未命名道路'}</strong><br>
                                        长度: ${this.formatDistance(segment.length)}<br>
                                        起点: ${segment.source} → 终点: ${segment.target}
                                    `);
                                    
                                    this.routeLayer.addLayer(polyline);
                                }
                            } catch (e) {
                                console.error('解析几何数据失败:', e);
                            }
                        }
                    });

                    // 添加起点和终点标记
                    if (this.routeResult.startNodeId) {
                        const startMarker = L.marker([39.9042, 116.4074], {
                            icon: L.divIcon({
                                className: 'start-marker',
                                html: '<div style="background: #67c23a; color: white; border-radius: 50%; width: 20px; height: 20px; display: flex; align-items: center; justify-content: center; font-weight: bold;">起</div>',
                                iconSize: [20, 20]
                            })
                        });
                        this.routeLayer.addLayer(startMarker);
                    }

                    if (this.routeResult.endNodeId) {
                        const endMarker = L.marker([31.2304, 121.4737], {
                            icon: L.divIcon({
                                className: 'end-marker',
                                html: '<div style="background: #f56c6c; color: white; border-radius: 50%; width: 20px; height: 20px; display: flex; align-items: center; justify-content: center; font-weight: bold;">终</div>',
                                iconSize: [20, 20]
                            })
                        });
                        this.routeLayer.addLayer(endMarker);
                    }

                    this.map.addLayer(this.routeLayer);
                    this.map.fitBounds(this.routeLayer.getBounds());
                },

                // 解析几何数据
                parseGeometry(geom) {
                    // 这里需要根据实际的几何数据格式进行解析
                    // 假设是WKT格式的LINESTRING
                    if (typeof geom === 'string' && geom.startsWith('LINESTRING')) {
                        const coordsStr = geom.replace('LINESTRING(', '').replace(')', '');
                        const coords = coordsStr.split(',').map(coord => {
                            const [x, y] = coord.trim().split(' ');
                            return [parseFloat(x), parseFloat(y)];
                        });
                        return coords;
                    }
                    return null;
                },

                // 清除路径
                clearRoute() {
                    if (this.routeLayer) {
                        this.map.removeLayer(this.routeLayer);
                        this.routeLayer = null;
                    }
                    this.routeResult = null;
                },

                // 居中地图
                centerMap() {
                    this.map.setView([39.9042, 116.4074], 6);
                },

                // 切换全屏
                toggleFullscreen() {
                    if (document.fullscreenElement) {
                        document.exitFullscreen();
                    } else {
                        document.documentElement.requestFullscreen();
                    }
                },

                // 格式化距离
                formatDistance(distance) {
                    if (distance == null) return '0 米';
                    if (distance < 1000) {
                        return Math.round(distance) + ' 米';
                    } else {
                        return (distance / 1000).toFixed(2) + ' 公里';
                    }
                }
            }
        }).use(ElementPlus).mount('#app');
    </script>
</body>
</html>
